<?php
namespace app\backstage\logic;
use think\Db;
class RecyclingReport
{
    /*列表数据获取*/
    public function getList($params)
    {
        $groupBy = 'report_date';
        $type = 1;
        $where = [];
        $uid = request()->_user->id;

        if( in_array(request()->_role->alias,['channel','agent']) )
        {
            $field_ac = 'report_date,new_fan_recharge,total_cost,accumulated_recharge,first_accumulated_recharge,';
            $field_ac .= 'first_consumption_amount,new_fan_num,pay_new_fan_num,accumulated_order_num,total_fan_num,';
            $field_ac .= 'pay_total_fan_num,accumulated_total_cost,first_order_num,';
            $field_ac .= 'first_annual_recharge,first_order_annual_num,t2,t3,t4,t5,t6,t7,t8,t9,t10,t11,t12,t13,t14,t15,t16';
            $field_ac .= ',t17,t18,t19,t20,t21,t22,t23,t24,t25,t26,t27,t28,t29,t30';

        }else{
            $field_ad = 'report_date,SUM(new_fan_recharge) AS new_fan_recharge,SUM(total_cost) AS total_cost,';
            $field_ad .= 'SUM(accumulated_recharge) AS accumulated_recharge,SUM(first_accumulated_recharge) AS first_accumulated_recharge,';
            $field_ad .= 'SUM(first_consumption_amount) AS first_consumption_amount,SUM(new_fan_num) AS new_fan_num,';
            $field_ad .= 'SUM(pay_new_fan_num) AS pay_new_fan_num,';
            $field_ad .= 'SUM(accumulated_order_num) as accumulated_order_num,SUM(total_fan_num) AS total_fan_num,';
            $field_ad .= 'SUM(pay_total_fan_num) AS pay_total_fan_num,';
            $field_ad .= 'SUM(accumulated_total_cost) AS accumulated_total_cost,SUM(first_order_num) AS first_order_num,';
            $field_ad .= 'SUM(first_annual_recharge) AS first_annual_recharge,SUM(first_order_annual_num) AS first_order_annual_num';
            $field_ad .= ',SUM(t2) AS t2,SUM(t3) AS t3,SUM(t4) AS t4,SUM(t5) AS t5,SUM(t6) AS t6,SUM(t7) AS t7,SUM(t8) AS t8,SUM(t9) AS t9';
            $field_ad .= ',SUM(t10) AS t10,SUM(t11) AS t11,SUM(t12) AS t12,SUM(t13) AS t13,SUM(t14) AS t14,SUM(t15) AS t15,SUM(t16) AS t16';
            $field_ad .= ',SUM(t17) AS t17,SUM(t18) AS t18,SUM(t19) AS t19,SUM(t20) AS t20,SUM(t21) AS t21,SUM(t22) AS t22,SUM(t23) AS t23';
            $field_ad .= ',SUM(t24) AS t24,SUM(t25) AS t25,SUM(t26) AS t26,SUM(t27) AS t27,SUM(t28) AS t28,SUM(t29) AS t29,SUM(t30) AS t30';
        }

        if(isset($params['channel_id']) && $params['channel_id'] > 0)
        {
            $where[] = ['channel_id','=',$params['channel_id']];
            $type = 6;
        }else{
            if(request()->_role->alias == 'agent')
            {
                $type = 1;
                $where[] = ['agent_id','=',$uid];
            }
            if(request()->_role->alias == 'channel')
            {
                $type = 6;
                $where[] = ['channel_id','=',$uid];
            }
        }

        if(isset($params['advert_media_id']) && $params['advert_media_id'] > 0)
        {
            $where[] = ['advert_media_id','=',$params['advert_media_id']];

            if($type == 6)
            {
                $type = 9;
            }else{
                $type = request()->_role->alias == 'channel' ? 9 : 4;
            }

        }

        if (isset($params['start_date']) && strlen($params['start_date']) > 1) {
            $where[] = ['report_date', '>=', $params['start_date']];
        }

        if (isset($params['end_date']) && strlen($params['end_date']) > 1) {
            $where[] = ['report_date', '<=', $params['end_date']];
        }

        if(isset($params['dimension']) && $params['dimension'] > 0)
        {
            $groupArr = [0 => '', 1 => 'advert_media_id', 2 => 'quick_id', 3 => 'link_id', 4 => 'quick_id'];
            $groupItem[] = $groupArr[$params['dimension'] - 1];
            if ($params['dimension'] > 1) {
                $groupBy = implode(',', $groupItem) . ',report_date';
            }

            if($params['dimension'] == 2)
            {
                if($type == 6 || $type == 9)
                {
                    $type = 9;
                }else{
                    $type = request()->_role->alias == 'channel' ? 9 : 4;
                }

            }else if($params['dimension'] == 3){
                if($type == 6 || $type == 7){
                    $type = 7;
                }else{
                    $type = request()->_role->alias == 'channel' ? 7 : 2;
                }

            }else if($params['dimension'] == 4){
                if($type == 6 || $type == 8)
                {
                    $type = 8;
                }else{
                    $type = request()->_role->alias == 'channel' ? 8 : 3;
                }

            }else if($params['dimension'] == 5){
                if($type == 6 || $type == 10)
                {
                    $type = 10;
                }else{
                    $type = request()->_role->alias == 'channel' ? 10 : 5;
                }

            }

        }

        $field = in_array(request()->_role->alias,['channel','agent']) ? $field_ac : $field_ad;

        if($type == 4 || $type == 9)
        {
            $field .= ',advert_media_id';
            $where[] = ['advert_media_id','>',0];
        }
        if($type == 5 || $type == 10)
        {
            $field .= ',quick_id';
            $where[] = ['quick_id','>',0];
        }

        if( isset($params['field']) ){
            $orderBy = [ $params['field'] => $params['order'] ];
        }else{
            $orderBy = ['report_date' => 'DESC'];
        }

        $RecyclingReport = \think\facade\App::model('RecyclingReport');
        $list = $RecyclingReport->getList($type,$where, $field, $params['page'], $params['limit'], $orderBy, $groupBy);
        if($list){

            $quick_id_gh = array_unique(array_column($list,'quick_id'));
            $quicks = Db::table('quick_app')->where('id','in',$quick_id_gh)->column('id,name');

            $todayTime = time();
            foreach($list as $k=>$v)
            {
                $list[$k]['day'] = $this->getDateDay($todayTime, $v['report_date']);
                $list[$k]['media_name'] = isset($v['advert_media_id']) ? getAdvertMediaName($v['advert_media_id']) : '';
                $list[$k]['quick_name'] = isset($v['quick_id']) && isset($quicks[$v['quick_id']]) ? $quicks[$v['quick_id']] : '';

                $total_cost                                 = getQuotient($v['total_cost'],100);
                $list[$k]['accumulated_recharge']           = getQuotient($v['accumulated_recharge'],100);
                $list[$k]['total_cost']                     = $total_cost;
                $new_fan_recharge                           = getQuotient($v['new_fan_recharge'],100);
                $list[$k]['new_fan_recharge']               = $new_fan_recharge;
                $accumulated_recovery_rate                  = getQuotient($v['accumulated_recharge'],$v['total_cost'],2,'m',100);
                $list[$k]['accumulated_recovery_rate']      = $accumulated_recovery_rate.'%';
                $list[$k]['first_roi']                      = getQuotient($v['new_fan_recharge'],$v['total_cost'],2,'m',100).'%';
                $list[$k]['fan_unit_price']                 = getQuotient($v['total_cost'],$v['new_fan_num'],3,'d',100);
                $list[$k]['pay_new_fan_unit_price']         = getQuotient($v['total_cost'],$v['pay_new_fan_num'],3,'d',100);
                $list[$k]['first_order_unit_price']         = getQuotient($v['first_accumulated_recharge'],$v['first_order_num'],2,'d',100);
                $list[$k]['new_fan_pay_rate']               = getQuotient($v['pay_new_fan_num'],$v['new_fan_num'],2,'m',100).'%';
                $list[$k]['new_fan_arpu']                   = getQuotient($v['new_fan_recharge'],$v['new_fan_num'],2,'d',100);
                //$list[$k]['new_fan_proportion']             = getQuotient($v['new_fan_num'],$v['total_fan_num'],2,'m',100).'%';
                //$list[$k]['shielded_area_fan_proportion']   = getQuotient($v['total_fan_num_shielded_area'],$v['total_fan_num'],2,'m',100).'%';
                $list[$k]['accumulated_pay_fan_unit_price'] = getQuotient($v['accumulated_total_cost'],$v['pay_total_fan_num'],3,'d',100);
                $list[$k]['accumulated_order_unit_price']   = getQuotient($v['accumulated_recharge'],$v['accumulated_order_num'],2,'d',100);
                $list[$k]['first_annual_proportion']        = getQuotient($v['first_order_annual_num'],$v['first_order_num'],2,'m',100).'%';
                $list[$k]['first_annual_recharge']          = getQuotient($v['first_annual_recharge'],100);

                $list[$k]['t1']                             = getQuotient($v['new_fan_recharge'],$v['total_cost'],2,'m',100);
                $list[$k]['rate_recovery_1']                = getQuotient($v['new_fan_recharge'],$v['total_cost'],2,'m',100).'%';
                $list[$k]['increase_1']                     = $new_fan_recharge;

                for ($i=2;$i<=30;$i++)
                {
                    $itemTime = $todayTime + (86400 * ($i - 1));
                    $dayIndex = $this->getItemDayIndex($todayTime, $itemTime);
                    if ($list[$k]['day'] >= $dayIndex){
                        $list[$k]['t'.$i]                         = getQuotient($v['t'.$i],$v['total_cost'],2,'m',100);
                        $list[$k]['increase_'.$i]                 = getQuotient($v['t'.$i],100);
                        $list[$k]['rate_recovery_'.$i]            = $this->getRangeRateDate($list[$k],$i);
                    }else{
                        $list[$k]['t'.$i]                         = '-';
                        $list[$k]['increase_'.$i]                 = '-';
                        $list[$k]['rate_recovery_'.$i]            = '-';
                    }
                }
            }

        }


        $result['count']    = $RecyclingReport->getTotalNumber($type,$where,$groupBy);

        return ['code' => 0, 'msg' => 'success', 'count' => $result['count'], 'data' => $list];
    }

    /*获取日期天数排序位*/
    private function getDateDay($todayTime, $date)
    {
        $startDate = strtotime($date);
        $secondsDiff = $todayTime - $startDate;
        $daysDiff = floor($secondsDiff / (60 * 60 * 24));
        return $daysDiff + 1;
    }

    /*未来日期和今天的相差值*/
    private function getItemDayIndex($todayTime, $time)
    {
        $today = date("Y-m-d", $todayTime);
        $startDate = strtotime($today);
        $secondsDiff = $time - $startDate;
        $daysDiff = floor($secondsDiff / (60 * 60 * 24));
        return $daysDiff + 1;
    }

    /*获取指定周期内的回收率总和*/
    private function getRangeRateDate($list,$index)
    {
        $t1 = getQuotient($list['new_fan_recharge'],$list['total_cost'],2,'m',100);
        $total_rate = 0;
        for ($i=2;$i<=30;$i++)
        {
            if($i<=$index)
            {
                $total_rate = $total_rate+$list['t'.$i];
            }
        }

        return $total_rate+$t1.'%';
    }

    /*获取汇总数据总和*/
    public function getTotal($params)
    {
        $field = 'sum(new_fan_recharge) as new_fan_recharge,sum(total_cost) as total_cost,sum(accumulated_recharge) as accumulated_recharge,';
        $field .= 'sum(first_accumulated_recharge) as first_accumulated_recharge,sum(first_consumption_amount) as first_consumption_amount,';
        $field .= 'sum(new_fan_num) as new_fan_num,sum(pay_new_fan_num) as pay_new_fan_num,';
        $field .= 'sum(accumulated_order_num) as accumulated_order_num,sum(total_fan_num) as total_fan_num,';
        $field .= 'sum(pay_total_fan_num) as pay_total_fan_num,sum(accumulated_total_cost) as accumulated_total_cost,';
        $field .= 'sum(first_order_num) as first_order_num,sum(first_annual_recharge) as first_annual_recharge,sum(first_order_annual_num) as first_order_annual_num';

        $type = 1;
        $where = []; //" 1=1 ";
        $uid = request()->_user->id;

        if(isset($params['channel_id']) && $params['channel_id'] > 0)
        {
            $where[] = ['channel_id','=',$params['channel_id']];
            $type = 6;
        }else{
            if(request()->_role->alias == 'agent')
            {
                $type = 1;
                $where[] = ['agent_id','=',$uid];
            }
            if(request()->_role->alias == 'channel')
            {
                $type = 6;
                $where[] = ['channel_id','=',$uid];
            }
        }

        if(isset($params['advert_media_id']) && $params['advert_media_id'] > 0)
        {
            $where[] = ['advert_media_id','=',$params['advert_media_id']];
            if($type == 6) {
                $type = 9;
            }else{
                $type = request()->_role->alias == 'channel' ? 9 : 4;
            }

        }

        if (isset($params['start_date']) && strlen($params['start_date']) > 1) {
            $where[] = ['report_date', '>=', $params['start_date']];
        }

        if (isset($params['end_date']) && strlen($params['end_date']) > 1) {
            $where[] = ['report_date', '<=', $params['end_date']];
        }

        if(isset($params['dimension']) && strlen($params['dimension']) > 0)
        {
            if($params['dimension'] == 2)
            {
                if($type == 6 || $type == 9)
                {
                    $type = 9;
                }else{
                    $type = request()->_role->alias == 'channel' ? 9 : 4;
                }

            }else if($params['dimension'] == 3){
                if($type == 6 || $type == 7){
                    $type = 7;
                }else{
                    $type = request()->_role->alias == 'channel' ? 7 : 2;
                }

            }else if($params['dimension'] == 4){
                if($type == 6 || $type == 8)
                {
                    $type = 8;
                }else{
                    $type = request()->_role->alias == 'channel' ? 8 : 3;
                }

            }else if($params['dimension'] == 5){
                if($type == 6 || $type == 10)
                {
                    $type = 10;
                }else{
                    $type = request()->_role->alias == 'channel' ? 10 : 5;
                }

            }
        }

        switch ($type)
        {
            case 1:
                $table = 'rp_recycling_report_daily_agent';
                break;
            case 2:
                $table = 'rp_recycling_report_daily_agent_quick';
                break;
            case 3:
                $table = 'rp_recycling_report_daily_agent_link';
                break;
            case 4:
                $table = 'rp_recycling_report_daily_agent_media';
                break;
            case 5:
                $table = 'rp_recycling_report_daily_agent_quick';
                break;
            case 6:
                $table = 'rp_recycling_report_daily_channel';
                break;
            case 7:
                $table = 'rp_recycling_report_daily_channel_quick';
                break;
            case 8:
                $table = 'rp_recycling_report_daily_channel_link';
                break;
            case 9:
                $table = 'rp_recycling_report_daily_channel_media';
                break;
            case 10:
                $table = 'rp_recycling_report_daily_channel_quick';
                break;
            default :
                $table = 'rp_recycling_report_daily';
        }


        if($type == 4 || $type == 9)
        {
            $where[] = ['advert_media_id','>',0];
        }
        if($type == 5 || $type == 10)
        {
            $where[] = ['quick_id','>',0];
        }

        $record = Db::table($table)->where($where)->field($field)->findOrEmpty();

        $record_list[0]['summary_title']                    = '总计';
        $total_cost                                         = getQuotient($record['total_cost'],100);
        $record_list[0]['total_cost']                       = $total_cost;
        $record_list[0]['new_fan_recharge']                 = getQuotient($record['new_fan_recharge'],100);
        $accumulated_recovery_rate                          = getQuotient($record['accumulated_recharge'],$record['total_cost'],2,'m',100);
        $record_list[0]['accumulated_recovery_rate']        = $accumulated_recovery_rate.'%';
        $record_list[0]['first_roi']                        = getQuotient($record['new_fan_recharge'],$record['total_cost'],2,'m',100).'%';
        $record_list[0]['fan_unit_price']                   = getQuotient($record['total_cost'],$record['new_fan_num'],3,'d',100);
        $record_list[0]['pay_new_fan_unit_price']           = getQuotient($record['total_cost'],$record['pay_new_fan_num'],3,'d',100);
        $record_list[0]['first_order_unit_price']           = getQuotient($record['first_accumulated_recharge'],$record['first_order_num'],2,'d',100);
        $record_list[0]['new_fan_pay_rate']                 = getQuotient($record['pay_new_fan_num'],$record['new_fan_num'],2,'m',100).'%';
        $record_list[0]['new_fan_arpu']                     = getQuotient($record['new_fan_recharge'],$record['new_fan_num'],2,'d',100);
        //$record_list[0]['new_fan_proportion']               = getQuotient($record['new_fan_num'],$record['total_fan_num'],2,'m',100).'%';
        //$record_list[0]['shielded_area_fan_proportion']     = getQuotient($record['total_fan_num_shielded_area'],$record['total_fan_num'],2,'m',100).'%';
        $record_list[0]['accumulated_pay_fan_unit_price']   = getQuotient($record['accumulated_total_cost'],$record['pay_total_fan_num'],3,'d',100);
        $record_list[0]['accumulated_order_unit_price']     = getQuotient($record['accumulated_recharge'],$record['accumulated_order_num'],2,'d',100);
        $record_list[0]['first_annual_proportion']          = getQuotient($record['first_order_annual_num'],$record['first_order_num'],2,'m',100).'%';
        $record_list[0]['accumulated_recharge']             = getQuotient($record['accumulated_recharge'],100);
        $record_list[0]['new_fan_num']                      = getFinalIntValue($record['new_fan_num']);
        $record_list[0]['pay_new_fan_num']                  = getFinalIntValue($record['pay_new_fan_num']);
        $record_list[0]['accumulated_order_num']            = getFinalIntValue($record['accumulated_order_num']);
        //$record_list[0]['total_fan_num']                    = getFinalIntValue($record['total_fan_num']);
        $record_list[0]['pay_total_fan_num']                = getFinalIntValue($record['pay_total_fan_num']);
        $record_list[0]['first_order_num']                  = getFinalIntValue($record['first_order_num']);
        $record_list[0]['first_annual_recharge']            = getQuotient($record['first_annual_recharge'],100);

        return ['code'=>0,'msg'=>'success','count'=>1,'data'=>$record_list];
    }

}